package xuanzhen.pro.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import xuanzhen.wx.util.EmojiFilter;
import xuanzhen.wx.util.SignUtil;
import xuanzhen.wx.util.fina.WxSet;
import xuanzhen.pro.pojo.Relay;
import xuanzhen.pro.service.RelayService;
import xuanzhen.wx.pojo.AccessToken;
import xuanzhen.wx.pojo.Jsticket;

import xuanzhen.wx.pojo.WxUserMsg;

import xuanzhen.wx.service.CoreService;

@Controller
@RequestMapping("/core")
public class CoreController {
	@Resource
	CoreService coreService;
	@Resource
	RelayService relayService;
	/**
	 * 确认请求来自微信服务器
	 */
	
	  @RequestMapping("/into") 
	  public Object into(HttpServletRequest request,HttpServletResponse response,Model model, HttpSession session)
	  throws IOException{ // 微信加密签名 
		  String signature = request.getParameter("signature"); // 时间戳
		  String timestamp = request.getParameter("timestamp"); // 随机数
		  String nonce = request.getParameter("nonce"); // 随机字符串
		  String echostr = request.getParameter("echostr");
		  
		  PrintWriter out = response.getWriter(); 
		  // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		  if(SignUtil.checkSignature(signature, timestamp, nonce)) {
		  out.print(echostr);
		  } 
		  out.close(); 
		  out = null;
		  return "foward:toRight.html"; 
	 }
	 
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
			session.setAttribute("opid","ceshi测试！");
			System.out.println("这是appid！！！！"+WxSet.APPID);
			session.setAttribute("nickName","测试！");
			long timestamp = System.currentTimeMillis() / 1000;
			String noncestr = RandomStringUtils.randomAlphanumeric(4);
			String relayNo=timestamp+noncestr;
			session.setAttribute("relayNo",relayNo);
		return "put";
	}
	@RequestMapping(value = "/errorPage.html", method = RequestMethod.GET)
	public String oops(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
			
			System.out.println("出现错误404");
			
			
		return "error";
	}
	@RequestMapping(value = "/inde", method = RequestMethod.GET)
	public String inre(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
			session.setAttribute("opid","dwdwafggrgrs");
			session.setAttribute("nickName","大先生");
			String reNo= "1476365514j9KO";
			session.setAttribute("relayNo", "1476365514j9KO");
			Relay re = relayService.selectRelayByRelayNo(reNo);
			session.setAttribute("relay", re);
			String reState=re.getRelayState();
			System.out.println(reState);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
			
		    long date = sdf.parse(re.getCreateTime()).getTime(); 
		    System.out.println(date);
		    session.setAttribute("date",date );
			
		    Date d = new Date();
		    System.out.println("现在"+d);
		    long n = d.getTime();
		    System.out.println("现在"+n);
		    double c =Math.floor((n-date)/1000);
		    System.out.println("差值"+c);
		    System.out.println("小时差"+c/3600);
		    session.setAttribute("c",c );
		  
		    	return "final";
		    
			
			
	}
	@RequestMapping(value = "/up", method = RequestMethod.GET)
	public String up(Model model, HttpSession session, HttpServletRequest req, HttpServletResponse response)
			throws Exception {
		// 获取时间戳
				long timestamp = System.currentTimeMillis() / 1000;
				session.setAttribute("timestamp", timestamp);
				// 生成随机字符串
				String noncestr = RandomStringUtils.randomAlphanumeric(16);
				session.setAttribute("noncestr", noncestr);
				String code="";
				 code = (String)session.getAttribute("code");
		// 当前网页url
				String url="";
				 url = req.getScheme() + "://" + req.getServerName() + req.getRequestURI();
				if (req.getQueryString() != null) {
					url += "?" + req.getQueryString();
				}
				System.out.println(url);
				Jsticket ticket=(Jsticket) session.getAttribute("ticket");
				// 签名
				String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
				session.setAttribute("signature", signature);
				return "final";
		
	}
	/**
	 * 跳转授权页面
	 */
	@RequestMapping(value = "/toRight.html", method = RequestMethod.GET)
	public void toRight(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println(WxSet.APPID);
		response.sendRedirect(coreService.getUserRight());
	}
	/**
	 * 接受跳转授权页面
	 */
	@RequestMapping(value = "/getRelay.html", method = RequestMethod.GET)
	public void toReRight(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 当前网页url
				String url = "";
				if (request.getQueryString() != null) {
					url += "?" + request.getQueryString();
				} 	
				response.sendRedirect(coreService.getReUserRight(url));
		 /*request.getRequestDispatcher(coreService.getReUserRight(url)).forward(request,response);*/
	}
	/**
	 * 获取授权
	 */
	@RequestMapping(value = "/getRight.html", method = RequestMethod.GET)
	public String getRight(Model model, HttpSession session, HttpServletRequest request) throws Exception {
		// 获取授权后code
		String code = request.getParameter("code");
		session.setAttribute("code", code);
		String state = request.getParameter("state");
		// 获取token
		AccessToken token = coreService.getAccessToken(code, state);
		System.out.println(token);
		// 获取用户微信信息
		WxUserMsg umsg = coreService.catchUserMsg(token);
		
		if(relayService.selectWxUserByOpenid(umsg.getOpenid())==null){
			String nk= EmojiFilter.filterEmoji(umsg.getNickname());
			umsg.setNickname(nk); 
			relayService.saveWxUser(umsg);
		}
		System.out.println(umsg);
		// 获得js票
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		session.setAttribute("ticket", ticket);
		System.out.println(ticket);
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		// 设置时间
		umsg.setCreatTime(nowTime);
		System.out.println(umsg);
		// appid
		session.setAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
				
			/*	"http://run.xuanzhen-tech.com/wx_project/user/getRight.html?code=" + code + "&state=STATE";*/
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		
		long Rtimestamp = System.currentTimeMillis() / 1000;
		String Rnoncestr = RandomStringUtils.randomAlphanumeric(4);
		String relayNo=Rtimestamp+Rnoncestr;
		session.setAttribute("relayNo",relayNo);
		String openId = umsg.getOpenid();
		session.setAttribute("opid", openId);
		String nickName = umsg.getNickname();
		session.setAttribute("nickName", nickName);

		return "put";
	}
	/**
	 * 获取授权
	 */
	@RequestMapping(value = "/jieshouHuoqu.html", method = RequestMethod.GET)
	public String getReRight(Model model, HttpSession session, HttpServletRequest request) throws Exception {
		// 获取授权后code
		String code = request.getParameter("code");
		session.setAttribute("code", code);
		String state = request.getParameter("state");
		// 获取token
		AccessToken token = coreService.getAccessToken(code, state);
		System.out.println(token);
		// 获取用户微信信息
		WxUserMsg umsg = coreService.catchUserMsg(token);
		if(relayService.selectWxUserByOpenid(umsg.getOpenid())==null){
			String nk= EmojiFilter.filterEmoji(umsg.getNickname());
			umsg.setNickname(nk); 
			relayService.saveWxUser(umsg);
		}
		System.out.println(umsg);
		// 获得js票
		AccessToken tokenCe = coreService.getAccessTokenC();
		Jsticket ticket = coreService.getJsticket(tokenCe);
		session.setAttribute("ticket", ticket);
		System.out.println(ticket);
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		// 获取时间戳
		long timestamp = System.currentTimeMillis() / 1000;
		session.setAttribute("timestamp", timestamp);
		// 生成随机字符串
		String noncestr = RandomStringUtils.randomAlphanumeric(16);
		session.setAttribute("noncestr", noncestr);
		// 设置时间
		umsg.setCreatTime(nowTime);
		System.out.println(umsg);
		// appid
		session.setAttribute("appid", WxSet.APPID);
		// 当前网页url
		String url = "";
		url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			url += "?" + request.getQueryString();
		} 		
				
			/*	"http://run.xuanzhen-tech.com/wx_project/user/getRight.html?code=" + code + "&state=STATE";*/
		// 签名
		String signature = coreService.getSignature(url, timestamp + "", noncestr, ticket.getTicket());
		session.setAttribute("signature", signature);
		String nickName = umsg.getNickname();
		session.setAttribute("nickName", nickName);
		String openId = umsg.getOpenid();

		session.setAttribute("opid", openId);
		String reNo= request.getParameter("relayNo");
		session.setAttribute("relayNo", reNo);
		Relay re = relayService.selectRelayByRelayNo(reNo);
		//时差判断
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	    long date = sdf.parse(re.getCreateTime()).getTime(); 	 
	    System.out.println(date);
	    long n = System.currentTimeMillis();
	    long c =(n-date)/1000;
	    System.out.println("差值"+c);
	    session.setAttribute("relay", re);
		session.setAttribute("date",date );
		session.setAttribute("c",c );
		String reState=re.getRelayState();
	   /* if(c<720000){
	    	//判定是否与发起人一致
			if(re.getSponsorOpenid().equals(openId)){
				if("normal".equals(reState)){
					return "begin";
				}else{
					return "wanc";
				}
			}else{
				if("normal".equals(reState)){
					return "index";
				}else{
					if(re.getRecipientOpenid().equals(openId)){
						return "wanc";
					}
					return "over";
				}
			}
	    }else{
	    	if("normal".equals(reState)){
				return "over";
			}else{
				if(re.getSponsorOpenid().equals(openId)){
					return "wanc";
				}else{
					return "over";
				}
			}
	    }*/
		//判定是否与发起人一致
		if(re.getSponsorOpenid().equals(openId)){
			if("normal".equals(reState)){
				return "begin";
			}else{
				return "wanc";
			}
		}else{
			if("normal".equals(reState)){
				return "index";
			}else{
				if(re.getRecipientOpenid().equals(openId)){
					return "wanc";
				}
				return "over";
			}
		}
	
		
		
		
	}
	
	
	/**

	    * 根据文件id下载文件

	    * 

	    * @param mediaId

	    *            媒体id

	    * @throws Exception

	    */

	   public  InputStream getInputStream(String mediaId,String accessToken) {

	     

	       InputStream is = null;

	       String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="

	               + accessToken + "&media_id=" + mediaId;

	       try {

	           URL urlGet = new URL(url);

	           HttpURLConnection http = (HttpURLConnection) urlGet

	                   .openConnection();

	           http.setRequestMethod("GET"); // 必须是get方式请求

	           http.setRequestProperty("Content-Type",

	                   "application/x-www-form-urlencoded");

	           http.setDoOutput(true);

	           http.setDoInput(true);

	           System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒

	           System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

	           http.connect();

	           // 获取文件转化为byte流

	           is = http.getInputStream();

	       } catch (Exception e) {

	           e.printStackTrace();

	       }

	       return is;

	   }

	   /**

	    * 获取下载图片信息（jpg）

	    * 

	    * @param mediaId

	    *            文件的id

	    * @throws Exception

	    */

	   public  void saveImageToDisk(String mediaId,String accessToken) throws Exception {
	       InputStream inputStream = getInputStream(mediaId,accessToken);
	       byte[] data = new byte[1024];
	       int len = 0;
	       FileOutputStream fileOutputStream = null;
	       try {
	           fileOutputStream = new FileOutputStream("test1.jpg");
	           while ((len = inputStream.read(data)) != -1) {
	               fileOutputStream.write(data, 0, len);
	           }
	       } catch (IOException e) {
	           e.printStackTrace();
	       } finally {
	           if (inputStream != null) {
	               try {
	                   inputStream.close();
	               } catch (IOException e) {
	                   e.printStackTrace();
	               }
	           }
	           if (fileOutputStream != null) {
	               try {
	                   fileOutputStream.close();
	               } catch (IOException e) {
	                   e.printStackTrace();
	               }
	           }
	       }
	   }
	
	
	
	
	
}
